<template>
  <div class="wrapper">
    <div class="banner">
      <div class="content">
        <swiper :options="swiperOption" ref="mySwiper" v-if="detail.imgList">
          <!-- slides -->
          <swiper-slide v-for="item of detail.imgList" :key="item.id">
            <img class="img" :src="item.url" preview="1">
          </swiper-slide>
          <!-- Optional controls -->
          <div class="swiper-pagination" slot="pagination"></div>
        </swiper>
      </div>
    </div>
    <div class='title'>
      <h3>{{ detail.title }}</h3>
      <p>{{ detail.describe }}</p>
      <h4 v-if="Array.isArray(detail.guagePriceRange)">￥{{ detail.guagePriceRange[0] | money }}~{{ detail.guagePriceRange[1] | money }}</h4>
      <h4 v-else-if="detail.guagePriceRange">￥{{ detail.guagePriceRange | money }}</h4>
      <h5 v-if="detail.freight">快递: {{ detail.freight | money }}元</h5>
      <h6 v-if="!isFutureMade">库存: {{ detail.totalStock }} 件</h6>
    </div>
    <div class="promise">
      正品保证
    </div>
    <div class="pick-guage" @click="show = true" v-if="!isFutureMade">
      {{ guage ? '已选择 ' + guageName + ' * ' + guageCount + '个' : '请选择规格' }}
    </div>
    <div class="goods-detail" v-html="detail.details">
      
    </div>
    <div class="buy-box">
      <router-link to="/shopCart" tag="div" class="shop-num">购物车({{ cartCount }})</router-link>
      <template v-if="!isFutureMade">
        <div class="add-shop" @click="shopcartAdd">加入购物车</div>
        <div class="buy-now" @click="buy">立刻购买</div>
      </template>
      <template v-else>
        <div class="buy-now">即将上市</div>
      </template>
    </div>
    <transition name="slide">
      <div class="slide-wrapper" v-if="show">
        <div class="title">
          <div class="img">
            <img :src="guageImage" preview>
          </div>
          <div class="name">
            <h3 v-if="Array.isArray(guagePrice)">￥{{ this.guagePrice[0] | money }}~￥{{ this.guagePrice[1] | money }}</h3>
            <h3 v-else>￥{{ this.guagePrice | money }}</h3>
            <h5>库存 {{ guageStock }} 件</h5>
          </div>
        </div>
        <p>规格</p>
        <div class="guage-list">
          <GuageList :guageList="detail.guageList" :currentGuage="guage" @pickGuage="pickGuage"></GuageList>
        </div>
        <div class="count">
          <div class="num">数量</div>
          <div class="ctrl">
            <CountCtrl :count="guageCount" :maxCount="guageStock" @change="changeCount"></CountCtrl>
          </div>
        </div>
        <div class="btn-wrapper">
          <button class="btn add-cart" @click="shopcartAdd">
            加入购物车
          </button>
          <button class="btn buy" @click="buy">
            立即购买
          </button>
        </div>
      </div>
    </transition>
    <Fade>
      <MaskView v-show="show" @click.native="show = false"></MaskView>
    </Fade>
  </div>
</template>

<script>
  import 'swiper/dist/css/swiper.css'
  import { swiper, swiperSlide } from 'vue-awesome-swiper'
  import MaskView from '@/components/mask/Mask.vue'
  import CountCtrl from '@/components/countCtrl/CountCtrl.vue'
  import GuageList from '@/components/guageList/GuageList.vue'
  import Fade from '@/components/fade/Fade.vue'
  import { mapState } from 'vuex'
  import _ from 'lodash'
  export default {
    name: 'GoodsDetail',
    components: {
      swiper,
      swiperSlide,
      GuageList,
      Fade,
      MaskView,
      CountCtrl
    },
    created() {
      /*
        get() 根据商品id请求详情
      */
      this._get()
      this._getCartLength()
    },
    data() {
      return {
        swiperOption: {
          initialSlide: 0
        },
        guage: '',
        guageImage: '',
        guagePrice: '',
        guageStock: '',
        guageCount: 1,
        guageName: '',
        cartCount: '0',
        detail: {},
        cartList: [],
        show: false
      }
    },
    computed: {
      ...mapState(['openId']),
      isFutureMade() {
        return this.detail.class_name == '新品预热'
      }
    },
    methods: {
      pickGuage(guage) {
        this.guage = guage.id
        this.guagePrice = guage.price
        this.guageImage = guage.url
        this.guageStock = Number(guage.stock)
        this.guageCount = 1
        this.guageName = guage.name
      },
      changeCount(data) {
        this.guageCount = data.count
      },
      async _getCartLength() {
        let { data: {code, data} } = await this.$axios({
          url: '/v1/cart/list',
          method: 'GET',
          params: {
            openid: this.openId,
            size: 1000,
            current: 1
          }
        })
        if(code == 0) {
          this.cartCount = data.items.length
        }
      },
      async _get() {
        let { data: { code, data } } = await this.$axios({
          url: '/v1/goods/list',
          method: 'GET',
          params: {
            id: this.$route.params.id,
            openid: this.openId
          }
        })
        if(code == 0) {
          //规格列表
          let guageList = data.gui.map(item => {
            item[0].count = 1
            item[0].price = item[0].price || item[0].m_price
            return item[0]
          })
          //图片列表
          let imgList = data.data.map(item => {
            return item[0]
          })
          //总库存
          let totalStock = 0
          guageList.forEach(item => {
            totalStock += Number(item.stock)
          })
          // 规格列表价格排序
          let guagePriceRange = guageList.map(item => {
            return Number(item.price)
          })
          if (guagePriceRange.length > 1) {
            guagePriceRange.sort((a, b) => {
              return a - b
            })
            guagePriceRange = [guagePriceRange[0], guagePriceRange[guagePriceRange.length - 1]]
            // guagePriceRange = '￥' + guagePriceRange[0] + '~￥' + guagePriceRange[guagePriceRange.length - 1]
          } else {
            guagePriceRange = guagePriceRange[0]
            // guagePriceRange = '￥' + guagePriceRange[0]
          }
          this.detail = {
            ...data.items[0],
            guageList,
            imgList,
            totalStock,
            guagePriceRange
          }
          //为后台返回的富文本html字符串中的img标签，动态挂载preview属性，使其能够使用vue-photo-preview插件查看大图
          this.$nextTick(() => {
            const detailImg = document.querySelectorAll('.goods-detail img')
            detailImg.forEach(item => {
              item.setAttribute('preview', '2')
            })
            this.$previewRefresh()
          })
          if (this.detail.guageList.length > 1) {
            this.guageImage = this.detail.imgList[0].url
            this.guagePrice = this.detail.guagePriceRange
            this.guageStock = Number(this.detail.totalStock)
          } else {
            this.guage = this.detail.guageList[0].id
            this.guageImage = this.detail.guageList[0].url
            this.guagePrice = this.detail.guageList[0].price
            this.guageStock = Number(this.detail.guageList[0].stock)
            this.guageName = this.detail.guageList[0].name
          }
        }
      },
      buy: _.throttle(async function() {
        if(!this.guage) {
          this.$toast('请选择规格')
          this.show = true
          return
        }
        let data = {
          title: this.detail.title,
          goods_id: this.detail.id,
          guageId: this.guage,
          guageName: this.guageName,
          price: this.guagePrice,
          num: this.guageCount,
          url: this.guageImage
        }
        this.$store.commit('payGoods', data)
        this.$router.push('/orderConfirmNow')
      }, 2000, { trailing: false }),
      shopcartAdd: _.throttle(async function() {
        if(!this.guage) {
          this.$toast('请选择规格')
          this.show = true
          return
        }
        let { data: { code, data } } = await this.$axios({
          url: '/v1/cart/increase',
          method: 'POST',
          data: {
            goods_id: this.detail.id,
            num: this.guageCount,
            hao_id: this.guage,
            openid: this.openId
          }
        })
        if(code == 0) {
          this.$toast(data)
          this._getCartLength()
          this.show = false
        }
      }, 2000, {
        trailing: false
      })
    }
  }
</script>

<style lang="scss" scoped>
  @import '@/assets/css/base.scss';
  .swiper-wrapper {
    align-items: center;
  }
  .slide-enter, .slide-leave-to {
    transform: translate3d(0, 100%, 0);
  }
  .slide-enter-active, .slide-leave-active {
    transition: all 0.2s linear;
  }
  .wrapper {
    padding-bottom: 1.75rem;
    background: #eee;
    min-height: 100vh;
  }
  .banner {
    position: relative;
    width: 100%;
    /* padding: 50%; */
    background: #fff;
    overflow: hidden;
    .content {
      width: 100%;
      height: 100%;
      /* position: absolute;
      top: 0;
      left: 0; */
      & /deep/ .swiper-wrapper {
        align-items: center;
      }
      .img {
        width: 100%;
      }
    }
  }
  .title {
    position: relative;
    padding: 0.2rem;
    background: #fff;
    margin-top: 0.2rem;
    h3 {
      margin-bottom: 0.06rem;
      font-size: 0.28rem;
    }
    p {
      margin-bottom: 0.1rem;
      font-size: 0.2rem;
      color: $colorGray;
    }
    h4 {
      margin-bottom: 0.1rem;
      font-size: 0.28rem;
      color: $colorRed;
      font-weight: bold;
    }
    h5 {
      color: #717171;
    }
    h6 {
      position: absolute;
      right: 0.2rem;
      bottom: 0.2rem;
      color: #717171;
    }
  }
  .promise, .pick-guage {
    margin-top: 0.2rem;
    padding-left: 0.2rem;
    background: #fff;
    height: 0.8rem;
    line-height: 0.8rem;
    font-size: 0.24rem;
  }
  .buy-box {
    position: fixed;
    display: flex;
    height: 0.8rem;
    background: #fff;
    width: 100%;
    bottom: 50px;
    box-shadow: 0 0 3px 1px #eee;
    .shop-num, .add-shop, .buy-now {
      height: 0.8rem;
      line-height: 0.8rem;
      text-align: center;
    }
    .shop-num {
      flex: 1;
    }
    .add-shop, .buy-now {
      flex: 0 0 2.4rem;
      width: 2.4rem;
      color: #fff;
    }
    .add-shop {
      background: orange;
    }
    .buy-now {
      background: $colorRed;
    }
  }
  .slide-wrapper {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 7rem;
    background: #fff;
    z-index: 11;
    .title {
      display: flex;
      align-items: center;
      padding: 0.2rem;
      height: 2rem;
      border-bottom: 1px solid $bgGray;
      .img {
        flex: 0 0 1.6rem;
        margin-right: 0.2rem;
        width: 1.6rem;
        height: 1.6rem;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .name {
        flex: 1;
        h3 {
          color: $colorRed;
        }
      }
    }
    p {
      margin-top: 0.2rem;
      padding-left: 0.2rem;
      font-size: 0.28rem;
    }
    .guage-list {
      padding: 0.2rem;
    }
    .count {
      display: flex;
      padding: 0.2rem;
      align-items: center;
      .num {
        flex: 1;
        font-size: 0.28rem;
      }
      .ctrl {
        flex: 0 0 1.5rem;
      }
    }
    .btn-wrapper {
      position: absolute;
      display: flex;
      bottom: 0;
      width: 100%;
      .btn {
        display: block;
        flex: 1;
        padding: 0.2rem;
        border: none;
        color: #fff;
        &.buy {
          background: $colorRed
        }
        &.add-cart {
          background: orange
        }
      }
    }
    
  }
  
</style>
<style lang="scss">
  .goods-detail {
    background: #fff;
    margin-top: 0.2rem;
    padding-bottom: 0.6rem;
    img {
      width:100% !important;
      height: auto;
    }
  }
</style>
